package com.example.service.impl;

import com.example.context.BaseContext;
import com.example.dto.ShoppingCartDTO;
import com.example.entity.Inventory;
import com.example.entity.Products;
import com.example.entity.ShoppingCart;
import com.example.entity.StoreShoppingCart;
import com.example.mapper.InventoryDao;
import com.example.mapper.ProductsDao;
import com.example.mapper.ShoppingCartDao;
import com.example.result.Result;
import com.example.service.ShoppingCartService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.PageRequest;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.List;

/**
 * 购物车(ShoppingCart)表服务实现类
 *
 * @author makejava
 * @since 2024-03-12 16:46:47
 */
@Service("shoppingCartService")
public class ShoppingCartServiceImpl implements ShoppingCartService {
    @Resource
    private ShoppingCartDao shoppingCartDao;

    @Autowired
    private ProductsDao productsDao;

    @Autowired
    private InventoryDao inventoryDao;

    /**
     * 通过ID查询单条数据
     *
     * @param id 主键
     * @return 实例对象
     */
    @Override
    public ShoppingCart queryById(Long id) {
        return this.shoppingCartDao.queryById(id);
    }

    /**
     * 分页查询
     *
     * @param shoppingCart 筛选条件
     * @param pageRequest      分页对象
     * @return 查询结果
     */
    @Override
    public Page<ShoppingCart> queryByPage(ShoppingCart shoppingCart, PageRequest pageRequest) {
        long total = this.shoppingCartDao.count(shoppingCart);
        return new PageImpl<>(this.shoppingCartDao.queryAllByLimit(shoppingCart, pageRequest), pageRequest, total);
    }

    /**
     * 新增数据
     *
     * @param shoppingCart 实例对象
     * @return 实例对象
     */
    @Override
    public ShoppingCart insert(ShoppingCart shoppingCart) {
        this.shoppingCartDao.insert(shoppingCart);
        return shoppingCart;
    }

    /**
     * 修改数据
     *
     * @param shoppingCart 实例对象
     * @return 实例对象
     */
    @Override
    public ShoppingCart update(ShoppingCart shoppingCart) {
        this.shoppingCartDao.update(shoppingCart);
        return this.queryById(shoppingCart.getId());
    }

    /**
     * 通过主键删除数据
     *
     * @param id 主键
     * @return 是否成功
     */
    @Override
    public boolean deleteById(Long id) {
        return this.shoppingCartDao.deleteById(id) > 0;
    }

    @Override
    public Result addShoppingCart(ShoppingCartDTO shoppingCartDTO) {
        ShoppingCart shoppingCart = new ShoppingCart();
        BeanUtils.copyProperties(shoppingCartDTO,shoppingCart);
        Long userId = BaseContext.getCurrentId();
        shoppingCart.setCustomerId(userId);

        List<ShoppingCart> list = shoppingCartDao.list(shoppingCart);



        //如果已存在，数量+1
        if(list != null && list.size()>0){
            //todo 判断库存
            List<Inventory> inventoryList = inventoryDao.queryByProductIdAndStoreId(list.get(0).getProductId(),list.get(0).getStoreId());
            ShoppingCart cart = list.get(0);
            if (inventoryList.get(0).getProductNum() <= cart.getNumber()){
                return Result.error("该商品已达库存上限");
            }
            cart.setNumber(cart.getNumber() + 1);
            shoppingCartDao.updateNumberById(cart);
            return Result.success(cart);
        }else{
            //如果不存在，需要插入一条购物车数据
            //判断本次添加到购物车的是菜品还是套餐
            Long dishId = shoppingCartDTO.getProductId();
            Long inventoryId = shoppingCartDTO.getInventoryId();
            if(dishId!=null){
                //本次添加到购物车的是菜品
                Products products = productsDao.getById(dishId);
                Inventory inventory = inventoryDao.queryById(inventoryId);
                shoppingCart.setName(products.getName());
                shoppingCart.setImage(products.getImage());
                shoppingCart.setAmount(products.getPrice());
                shoppingCart.setProductNum(inventory.getProductNum());
            }
            shoppingCart.setNumber(1);
            shoppingCart.setCreateTime(LocalDateTime.now());
            shoppingCartDao.insert(shoppingCart);
        }

        return Result.success(shoppingCart);
    }

    @Override
    public List<ShoppingCart> showShoppingCart(Long storeId) {
        Long userId = BaseContext.getCurrentId();
        ShoppingCart shoppingCart = ShoppingCart.builder()
                .id(userId)
                .storeId(storeId)
                .build();
        List<ShoppingCart> list = shoppingCartDao.list(shoppingCart);
        return list;
    }

    @Override
    public void cleanShoppingCart(Long storeId) {
        Long userId = BaseContext.getCurrentId();
        shoppingCartDao.deleteByUserId(userId,storeId);
    }

    @Override
    public void sub(ShoppingCartDTO shoppingCartDTO) {
        Long productId = shoppingCartDTO.getProductId();
        ShoppingCart shoppingCart = new ShoppingCart();
        BeanUtils.copyProperties(shoppingCartDTO,shoppingCart);
        if(productId != null ){
            List<ShoppingCart> list = shoppingCartDao.list(shoppingCart);
            Integer number = list.get(0).getNumber();
            if(list.get(0).getNumber()>1){
                list.get(0).setNumber(number-1);
                shoppingCartDao.updateNumberById(list.get(0));
            }else{
                shoppingCartDao.deleteById(list.get(0).getId());
            }
        }
    }
}
